<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" placeholder="用户名：s">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="loginForm.password" type="password" placeholder="密码：1" show-password autocomplete="new-password">
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="validCode">
      <div style="display: flex; align-items: center">
        <el-input v-model="loginForm.validCode" placeholder="请输入验证码" style="width: 50%" />
        <ValidCode v-model="generatedCode" style="margin-left: 20px" />
      </div>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button :icon="CircleClose" round size="large" @click="resetForm(loginFormRef)"> 重置 </el-button>
    <el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)">
      登录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
// import { getTimeState } from "@/utils";
import { Login } from "@/api/interface";
import ValidCode from "./ValidCode.vue";
import { ElMessage, ElNotification } from "element-plus";
import { loginApis } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import md5 from "md5";
import { getTimeState } from "@/utils";
import { useInfoStore } from "@/stores/modules/info";

const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();
const userInfo = useInfoStore();
type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();

const generatedCode = ref("");
const loginRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  validCode: [
    {
      validator: (rule: any, value: string, callback: any) => {
        if (!value) {
          ElMessage.error("请输入验证码");
          return callback(new Error("请输入验证码"));
        }
        if (value.toLowerCase() !== generatedCode.value.toLowerCase()) {
          ElMessage.error("验证码错误");
          return;
        }
        callback();
      },
      trigger: "blur"
    }
  ]
});

const loading = ref(false);
// const loginForm = reactive<Login.ReqLoginForm>({
//   username: "admin",
//   password: "123456"
// });
const loginForm = reactive({
  username: "s",
  password: "1",
  validCode: ""
});

// login
// const login = (formEl: FormInstance | undefined) => {
//   if (!formEl) return;
//   formEl.validate(async valid => {
//     if (!valid) return;
//     loading.value = true;
//     try {
//       // 1.执行登录接口
//       const { data } = await loginApi({ ...loginForm, password: md5(loginForm.password) });
//       // 存放token以及用户信息
//       userStore.setToken(data.access_token);
//       userStore.setName(data.name);
//       userStore.setavatar(data.avatar);
//       // 2.添加动态路由
//       await initDynamicRouter();

//       // 3.清空 tabs、keepAlive 数据
//       tabsStore.setTabs([]);
//       keepAliveStore.setKeepAliveName([]);

//       // 4.跳转到首页
//       router.push(HOME_URL);
//       ElNotification({
//         title: getTimeState(),
//         message: "欢迎登录 TZH-Admin",
//         type: "success",
//         duration: 3000
//       });
//     } finally {
//       loading.value = false;
//     }
//   });
// };
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      loginForm.password = md5(loginForm.password);
      // 1.执行登录接口
      const { data } = await loginApis(loginForm);
      console.log("loginForm", loginForm);
      console.log("data", data);
      // 存放token以及用户信息
      userInfo.setInfo({
        avatar: data.avatar,
        email: data.email,
        address: data.address,
        sex: data.sex,
        age: data.age,
        nickName: data.nickName,
        username: data.username
      });
      userStore.setUserId(data.id);
      userStore.setToken(data.token);
      userStore.setName(data.nickName);
      userStore.setavatar(data.avatar);
      // 直接调用新的方法来打印！
      userStore.printState();
      // 2.添加动态路由
      await initDynamicRouter();

      // // 3.清空 tabs、keepAlive 数据
      tabsStore.setTabs([]);
      keepAliveStore.setKeepAliveName([]);

      // // 4.跳转到首页
      router.push(HOME_URL);
      ElNotification({
        title: getTimeState(),
        message: "欢迎登录 TZH-Admin",
        type: "success",
        duration: 3000
      });
    } finally {
      loading.value = false;
    }
  });
};
// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});

onBeforeUnmount(() => {
  document.onkeydown = null;
});
</script>

<style scoped lang="scss">
@import "../index";
</style>
